package com.six.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.six.core.entity.Emp;
import com.six.core.entity.Permission;
import com.six.core.mapper.EmpMapper;
import com.six.core.mapper.PermissionMapper;
import com.six.core.service.PermissionService;

import com.six.core.util.JwtUtil;
import com.six.core.util.WebUtil;
import com.six.core.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * @Description:
 * @author:LiWei
 * @date:2023年02月27日15:38
 */
@Service
public class PermissionServiceImpl  implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result findByEmpId() {
        String token = WebUtil.getRequest().getHeader("token");
        Map<String, Object> tokenChaim = JwtUtil.decodeJWT(token);
        String username = (String) tokenChaim.get("username");

        QueryWrapper<Emp> empQueryWrapper = new QueryWrapper<>();
        empQueryWrapper.eq("username", username);
        Emp emp = empMapper.selectOne(empQueryWrapper);

        Integer id = emp.getId();
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.eq("id",id);
        List<Permission> permissions = permissionMapper.findPermissionById(id);
//        if (id.equals(id)) {
//            Stream<Emp> list = (Stream<Emp>) new ArrayList();
//            Stream<Emp> stream=list.filter()
//
//        }

//        System.out.println(permissions);

        List<Permission> firsts = firsts (permissions);
        return new Result(200,"查询成功",firsts);


    }
    private List<Permission> firsts(List<Permission> permissions){
        //1.一级菜单
        List<Permission> firsts= new ArrayList<>();

        for (Permission permission:permissions){
            if(permission.getPid().equals(0)){
                firsts.add(permission);
            }
        }
        //2.查询一级菜单下的二级菜单
        for(Permission first:firsts){
            List<Permission> children=new ArrayList<>();
            for(Permission p:permissions){
                if((first.getId()).equals(p.getPid())){
                    children.add(p);
                }
            }
            first.setChildren(children);
        }
        return firsts;
    }


    @Override
    public List<Permission> findByPermission (Integer id){
        List<Permission> permission = permissionMapper.findPermissionById(id);
        return permission;
    }
}













